# scores/crud.py
from sqlalchemy.orm import Session
from typing import List, Optional, Tuple
from . import models, schemas


class CRUDScore:
    def get(self, db: Session, student_id: str, exam_sequence: int) -> Optional[models.Score]:
        return db.query(models.Score).filter(
            models.Score.student_id == student_id,
            models.Score.exam_sequence == exam_sequence
        ).first()

    def get_by_student(self, db: Session, student_id: str) -> List[models.Score]:
        return db.query(models.Score).filter(models.Score.student_id == student_id).all()

    def get_all(self, db: Session, skip: int = 0, limit: int = 100) -> List[models.Score]:
        return db.query(models.Score).offset(skip).limit(limit).all()

    def create(self, db: Session, score_in: schemas.ScoreCreate) -> models.Score:
        db_score = models.Score(**score_in.dict())
        db.add(db_score)
        db.commit()
        db.refresh(db_score)
        return db_score

    def update(self, db: Session, student_id: str, exam_sequence: int, score_in: schemas.ScoreUpdate) -> Optional[models.Score]:
        db_score = self.get(db, student_id, exam_sequence)
        if db_score:
            update_data = score_in.dict(exclude_unset=True)
            for field, value in update_data.items():
                setattr(db_score, field, value)
            db.commit()
            db.refresh(db_score)
            return db_score

    def delete(self, db: Session, student_id: str, exam_sequence: int) -> bool:
        db_score = self.get(db, student_id, exam_sequence)
        if db_score:
            db.delete(db_score)
            db.commit()
            return True
        return False


crud_score = CRUDScore()